<template>
  <AdminLayout title="产品管理" subtitle="管理所有产品">
    <template #actions>
      <Link :href="route('admin.products.create')" 
            class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200">
        <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
        添加产品
      </Link>
    </template>

    <!-- 筛选器 -->
    <div class="mb-6 bg-white shadow-sm rounded-lg p-6">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
        <!-- 搜索 -->
        <div class="lg:col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-2">搜索产品</label>
          <input
            v-model="filters.search"
            type="text"
            placeholder="产品名称或 SKU..."
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          />
        </div>

        <!-- 分类筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">产品分类</label>
          <select
            v-model="filters.category_id"
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          >
            <option value="">全部分类</option>
            <option v-for="category in categories" :key="category.id" :value="category.id">
              {{ category.name }}
            </option>
          </select>
        </div>

        <!-- 状态筛选 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
          <select
            v-model="filters.is_active"
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          >
            <option value="">全部状态</option>
            <option value="1">启用</option>
            <option value="0">禁用</option>
          </select>
        </div>

        <!-- 产品类型 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">产品类型</label>
          <select
            v-model="filters.product_type"
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          >
            <option value="">全部类型</option>
            <option value="single">单规格</option>
            <option value="multi_variant">多规格</option>
          </select>
        </div>

        <!-- 推荐状态 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">推荐状态</label>
          <select
            v-model="filters.is_featured"
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          >
            <option value="">全部</option>
            <option value="1">推荐产品</option>
            <option value="0">普通产品</option>
          </select>
        </div>

        <!-- 库存状态 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">库存状态</label>
          <select
            v-model="filters.stock_status"
            class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
          >
            <option value="">全部</option>
            <option value="normal">库存正常</option>
            <option value="low">库存不足</option>
            <option value="out">已售罄</option>
          </select>
        </div>

        <!-- 价格区间 -->
        <div class="lg:col-span-2">
          <label class="block text-sm font-medium text-gray-700 mb-2">价格区间</label>
          <div class="flex items-center gap-2">
            <input
              v-model="filters.price_min"
              type="number"
              placeholder="最低价"
              class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            />
            <span class="text-gray-500">-</span>
            <input
              v-model="filters.price_max"
              type="number"
              placeholder="最高价"
              class="flex-1 px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
            />
          </div>
        </div>
      </div>

      <!-- 筛选按钮 -->
      <div class="flex items-center justify-between">
        <div class="text-sm text-gray-600">
          共 {{ products.length }} 个产品
        </div>
        <div class="flex gap-2">
          <button
            @click="resetFilters"
            class="px-4 py-2 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
          >
            重置
          </button>
          <button
            @click="applyFilters"
            class="px-4 py-2 border border-transparent rounded-md text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors"
          >
            应用筛选
          </button>
        </div>
      </div>
    </div>

    <!-- 状态切换确认对话框 -->
    <ConfirmDialog
      :show="showStatusDialog"
      :title="statusDialogData.action === 'enable' ? '启用产品' : '禁用产品'"
      :message="statusMessage"
      type="warning"
      confirm-text="确定"
      @close="showStatusDialog = false"
      @confirm="confirmStatusChange"
    />

    <!-- 推荐状态切换确认对话框 -->
    <ConfirmDialog
      :show="showFeaturedDialog"
      :title="featuredDialogData.action === 'feature' ? '设为推荐产品' : '取消推荐'"
      :message="featuredMessage"
      type="info"
      confirm-text="确定"
      @close="showFeaturedDialog = false"
      @confirm="confirmFeaturedChange"
    />

    <!-- 删除确认对话框 -->
    <ConfirmDialog
      :show="showDeleteDialog"
      title="删除产品"
      :message="deleteMessage"
      warning="如果该产品有订单记录，删除前请先处理相关订单。"
      type="danger"
      confirm-text="删除"
      @close="showDeleteDialog = false"
      @confirm="confirmDelete"
    />

    <!-- 产品列表 -->
    <div class="bg-white shadow-sm rounded-lg">
      <div class="px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-medium text-gray-900">产品列表</h3>
      </div>
      
      <div class="overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                产品信息
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                价格
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                类型
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                库存
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                分类
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="product in products" :key="product.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex items-center">
                  <div class="flex-shrink-0 h-12 w-12">
                    <div class="h-12 w-12 rounded-lg bg-gray-100 flex items-center justify-center">
                      <svg class="h-8 w-8 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
                      </svg>
                    </div>
                  </div>
                  <div class="ml-4">
                    <div class="text-sm font-medium text-gray-900">{{ product.name }}</div>
                    <div class="text-sm text-gray-500">{{ product.slug }}</div>
                  </div>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">¥{{ formatPrice(product.price) }}</div>
                <div v-if="product.compare_price" class="text-sm text-gray-500">
                  原价: ¥{{ formatPrice(product.compare_price) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="[
                  product.product_type === 'multi_variant' 
                    ? 'bg-blue-100 text-blue-800' 
                    : 'bg-green-100 text-green-800',
                  'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium'
                ]">
                  {{ product.product_type === 'multi_variant' ? '多规格' : '单规格' }}
                </span>
                <div v-if="product.product_type === 'multi_variant'" class="text-xs text-gray-500 mt-1">
                  {{ product.variants_count }} 个规格型号
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                {{ product.stock_quantity }}
              </td>
              <td class="px-6 py-4">
                <div v-if="product.categories.length > 0" class="flex flex-wrap gap-1">
                  <span v-for="category in product.categories" :key="category" 
                        class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                    {{ category }}
                  </span>
                </div>
                <span v-else class="text-sm text-gray-500">未分类</span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="flex flex-col space-y-1">
                  <span :class="[
                    product.is_active 
                      ? 'bg-green-100 text-green-800' 
                      : 'bg-red-100 text-red-800',
                    'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium'
                  ]">
                    {{ product.is_active ? '启用' : '禁用' }}
                  </span>
                  <span v-if="product.is_featured" 
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                    推荐
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <div class="flex space-x-2">
                  <Link :href="route('admin.products.edit', product.id)" 
                        class="text-gray-600 hover:text-gray-900 transition-colors duration-200">
                    编辑
                  </Link>
                  <Link v-if="product.product_type === 'multi'" 
                        :href="route('admin.products.variants', product.id)" 
                        class="text-blue-600 hover:text-blue-900 transition-colors duration-200">
                    规格型号
                  </Link>
                  <button @click="toggleStatus(product)" 
                          :class="[
                            product.is_active 
                              ? 'text-red-600 hover:text-red-900' 
                              : 'text-green-600 hover:text-green-900',
                            'transition-colors duration-200'
                          ]">
                    {{ product.is_active ? '禁用' : '启用' }}
                  </button>
                  <button @click="toggleFeatured(product)" 
                          :class="[
                            product.is_featured 
                              ? 'text-yellow-600 hover:text-yellow-900' 
                              : 'text-blue-600 hover:text-blue-900',
                            'transition-colors duration-200'
                          ]">
                    {{ product.is_featured ? '取消推荐' : '设为推荐' }}
                  </button>
                  <button @click="deleteProduct(product)" 
                          class="text-red-600 hover:text-red-900 transition-colors duration-200">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import ConfirmDialog from '@/Components/ConfirmDialog.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  products: {
    type: Array,
    required: true
  },
  categories: {
    type: Array,
    default: () => []
  }
})

// 通知功能
const { showSuccess, showError } = useNotification()

// 筛选器
const filters = ref({
  search: '',
  category_id: '',
  is_active: '',
  product_type: '',
  is_featured: '',
  stock_status: '',
  price_min: '',
  price_max: ''
})

// 应用筛选
const applyFilters = () => {
  router.get(route('admin.products.index'), filters.value, {
    preserveState: true,
    preserveScroll: true
  })
}

// 重置筛选
const resetFilters = () => {
  filters.value = {
    search: '',
    category_id: '',
    is_active: '',
    product_type: '',
    is_featured: '',
    stock_status: '',
    price_min: '',
    price_max: ''
  }
  applyFilters()
}

// 状态切换对话框
const showStatusDialog = ref(false)
const statusDialogData = ref({
  id: null,
  name: '',
  action: 'enable'
})

// 推荐状态切换对话框
const showFeaturedDialog = ref(false)
const featuredDialogData = ref({
  id: null,
  name: '',
  action: 'feature'
})

// 删除确认对话框
const showDeleteDialog = ref(false)
const deleteDialogData = ref({
  id: null,
  name: ''
})

const formatPrice = (price) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(price)
}

const toggleStatus = (product) => {
  statusDialogData.value = {
    id: product.id,
    name: product.name,
    action: product.is_active ? 'disable' : 'enable'
  }
  showStatusDialog.value = true
}

const confirmStatusChange = () => {
  router.post(route('admin.products.toggle-status', statusDialogData.value.id), {}, {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      showStatusDialog.value = false
    },
    onError: () => {
      showError('操作失败', '状态切换失败，请重试')
    }
  })
}

const toggleFeatured = (product) => {
  featuredDialogData.value = {
    id: product.id,
    name: product.name,
    action: product.is_featured ? 'unfeature' : 'feature'
  }
  showFeaturedDialog.value = true
}

const confirmFeaturedChange = () => {
  router.post(route('admin.products.toggle-featured', featuredDialogData.value.id), {}, {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      showFeaturedDialog.value = false
    },
    onError: () => {
      showError('操作失败', '推荐状态切换失败，请重试')
    }
  })
}

const deleteProduct = (product) => {
  deleteDialogData.value = {
    id: product.id,
    name: product.name
  }
  showDeleteDialog.value = true
}

const confirmDelete = () => {
  router.delete(route('admin.products.destroy', deleteDialogData.value.id), {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      showDeleteDialog.value = false
    },
    onError: () => {
      showError('删除失败', '删除产品失败，请重试')
    }
  })
}

// 计算属性
const statusMessage = computed(() => {
  const action = statusDialogData.value.action === 'enable' ? '启用' : '禁用'
  return `确定要${action}产品"${statusDialogData.value.name}"吗？`
})

const featuredMessage = computed(() => {
  const action = featuredDialogData.value.action === 'feature' ? '设为推荐' : '取消推荐'
  return `确定要${action}产品"${featuredDialogData.value.name}"吗？`
})

const deleteMessage = computed(() => {
  return `确定要删除产品"${deleteDialogData.value.name}"吗？此操作不可恢复！`
})
</script>
